package com.example.homelicaisystem.control;

import com.example.homelicaisystem.entity.*;
import com.example.homelicaisystem.entity.DTO.IncomeDetailDTO;
import com.example.homelicaisystem.entity.exception.UsedCashException;
import com.example.homelicaisystem.services.CardService;
import com.example.homelicaisystem.services.FamilyService;
import com.example.homelicaisystem.services.IncomeDetailService;
import com.example.homelicaisystem.services.UserService;
import com.example.homelicaisystem.utils.HandleMoney;
import com.example.homelicaisystem.utils.Result;
import com.example.homelicaisystem.utils.UserUtil;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/incomeDetail")
@RestController
@Slf4j
public class IncomeDetailControl {
    private final CardService cardService;
    private final IncomeDetailService incomeDetailService;
    private final UserService userService;

    public IncomeDetailControl(IncomeDetailService incomeDetailService, UserService userService, CardService cardService, FamilyService familyService) {
        this.incomeDetailService = incomeDetailService;
        this.userService = userService;
        this.cardService = cardService;
    }


    private static int BANK = 3;

    @PostMapping("/list")
    public Result<ListWithCount<IncomeDetail>> getList(@RequestBody IncomeDetailDTO data) {
        log.debug("收到请求list请求。参数:{}", data);
        //根据当前使用用户获取家庭id
        User user = userService.getUserById(UserUtil.getUserId());

        data.setFamilyId(user.getFamilyId());

        Page<IncomeDetail> res = incomeDetailService.getList(data);

        //数据库中金额单位为 分  前台单位为  元
        res.forEach(incomeDetail -> {
            incomeDetail.setMoney(HandleMoney.showMoney(incomeDetail.getMoney()));
        });

        return Result.ok(new ListWithCount<>(res.getTotal(), res));
    }

    @DeleteMapping("/delete/{id}")
//    没有返回值，泛型用？
    public Result<?> delete(@PathVariable int id) {
        log.debug("收到delete请求。");

        IncomeDetail incomeDetail = incomeDetailService.getIncomeDetailById(id);
        //业务为银行卡
        if (incomeDetail.getModeId() == BANK) {
            try {
                cardService.decreaseBank(incomeDetail);
            } catch (UsedCashException w) {
                throw new UsedCashException("银行卡金额已被使用，无法删除");
            }
        } else {
            try {
                userService.decreaseCash(incomeDetail);
            } catch (UsedCashException w) {
                throw new UsedCashException("此金额已被使用，无法删除");
            }
        }
        //删除
        incomeDetailService.delete(id);
        return Result.ok(null);
    }

    @PatchMapping("/modify")
    public Result<?> modify(@RequestBody IncomeDetail data) {
        log.debug("收到modify请求。参数:{}", data);
        //拿到后台处理时，金钱单位为最小单位 分
        data.setMoney(HandleMoney.backendMoney(data.getMoney()));
        //记录旧收入记录
        IncomeDetail oldIncome = incomeDetailService.getIncomeDetailById(data.getId());
        int changeMoney = 0;
        int dataMoney = data.getMoney();
        int oldMoney = oldIncome.getMoney();
        //判断更改后的金额与更改前的大小
        if (oldIncome.getMoney() <= dataMoney) {
            changeMoney = dataMoney - oldMoney;
            data.setMoney(changeMoney);
            //大就增加金钱
            if (data.getModeId() == BANK) {
                cardService.increaseBank(data);
            } else {
                userService.increaseCash(data);
            }
        } else {
            changeMoney = dataMoney - oldIncome.getMoney();
            data.setMoney(changeMoney);
            if (data.getModeId() == BANK) {
                cardService.decreaseBank(data);
            } else {
                userService.decreaseCash(data);
            }
        }

        data.setMoney(dataMoney);
        incomeDetailService.modify(data);
        return Result.ok(null);
    }

    @PostMapping("/create")
    public Result<Integer> create(@RequestBody IncomeDetail data) {
        log.debug("收到create请求。参数:{}", data);
        //拿到后台处理时，金钱单位为最小单位 分
        data.setMoney(HandleMoney.backendMoney(data.getMoney()));
        if (data.getModeId() == BANK) {
            cardService.increaseBank(data);
        } else {
            //1 为默认卡 及当业务为微信 支付宝时使用
            userService.increaseCash(data);
            data.setCardId(1);
        }

        //创建收入明细
        incomeDetailService.create(data);
        return Result.ok(data.getId());
    }

    @PostMapping("/selectIncomeType")
    public Result<List<SelectResult>> selectIncomeType() {
        log.debug("收到selectIncomeType请求");
        return Result.ok(incomeDetailService.selectIncomeType());
    }

    @PostMapping("/selectIncomeMode")
    public Result<List<SelectResult>> selectIncomeMode() {
        log.debug("收到selectIncomeMode请求");
        return Result.ok(incomeDetailService.selectIncomeMode());
    }
}
